/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-07-28
 * Time: 19:14
 */
class Solution20 {
    public int monotoneIncreasingDigits(int n) {
        //1.把数字串转换成字符数组
        char[] ch = Integer.toString(n).toCharArray();
        int i= 0,m = ch.length;

        while(i+1 < m && ch[i] <= ch[i+1]) {
            i++;
        }

        //判断特殊情况
        if(i == m-1) {
            return n;
        }

        //回退
        while(i-1 >= 0 && ch[i] == ch[i-1]) {
            i--;
        }

        ch[i]--;

        for(int j = i+1; j < m; j++) {
            ch[j] = '9';
        }

        return Integer.parseInt(new String(ch));
    }
}
